package com.sdy.hospitalguard.embed.keepalive.manager.netty.hander;

import com.alibaba.fastjson.JSONObject;
import com.sdy.common.utils.DateUtil;
import com.sdy.hospitalguard.embed.keepalive.init.HttpAccessRecordThread;
import com.sdy.hospitalguard.embed.keepalive.manager.netty.factory.HttpResponseFactory;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

@Slf4j
public class HttpResponseHander extends ChannelInboundHandlerAdapter {

    private static final String PERSON_VERIFICATION = "/LAPI/V1.0/System/Event/Notification/PersonVerification";
    private final String APPLICATION_JSON = "application/json";
    public static final String CONTENT_LENGTH = "Content-Length";
    public static final String CONTENT_TYPE = "Content-Type";
    public volatile String serialNo;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        try {
            if (msg instanceof FullHttpResponse) {
                FullHttpResponse response = (FullHttpResponse) msg;
                HttpResponseFactory.responseHandle(ctx, response);
            }else if (msg instanceof FullHttpRequest){
                FullHttpRequest request = (FullHttpRequest) msg;
                String res = request.content().toString(CharsetUtil.UTF_8);
                HttpAccessRecordThread.blockingQueue.offer(res);
                if (request.uri().contains(PERSON_VERIFICATION)){
                    // 回包
                    getHeartInfo(ctx, res);
                }else{
                    ctx.fireChannelRead(msg);
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 识别数据
     */
    private void getHeartInfo(ChannelHandlerContext ctx, String res) throws Exception {
        JSONObject object = JSONObject.parseObject(res);
        // 获取当前记录的通知记录序号
        ctx.writeAndFlush(getHeartBackBytebuff(object.getInteger("Seq")));
        log.info("识别记录回包正常！客户端IP: {}", ctx.channel().remoteAddress());
    }

    /**
     * 识别数据回包拼装
     *
     * @return
     * @throws Exception
     */
    private FullHttpResponse getHeartBackBytebuff(Integer seq) throws Exception {
        // 回包数据
        JSONObject object = new JSONObject(true);
        JSONObject res = new JSONObject(true);
        res.put("ResponseURL", "/LAPI/V1.0/PACS/Controller/Event/Notifications");
        res.put("StatusCode", 0);
        res.put("StatusString", "Succeed");
        JSONObject data = new JSONObject(true);
        data.put("RecordID", seq);
        data.put("Time", DateUtil.formatTime(new Date()));
        res.put("Data", data);
        object.put("Response", res);
        String strBody = JSONObject.toJSONString(object);
        FullHttpResponse response = new DefaultFullHttpResponse(
                HTTP_1_1, OK, Unpooled.wrappedBuffer(strBody.getBytes()));
        response.headers().set(CONTENT_LENGTH,
                response.content().readableBytes());
        response.headers().set(CONTENT_TYPE, APPLICATION_JSON);
        return response;
    }

}
